var rp = require("request-promise");
const { Op } = require("sequelize");
exports.getwhere = function (query) {
  let conds = [];
  let where = { [Op.and]: conds };
  for (let atr in query) {
    if (["pageNum", "pageSize"].includes(atr)) continue;
    if (query[atr]) {
      if (atr == "area") {
        var area = sequelize.fn("ST_GeomFromText", query[atr]);
        conds.push(
          sequelize.where(
            sequelize.fn("ST_Intersects", sequelize.col("geom"), area),
            true
          )
        );
      } else if (atr.substr(0, 6) == "_list_") {
        conds.push({ [atr.substr(6)]: query[atr].split(",") });
      } else if(atr.substr(0, 7) == "_start_"){
        conds.push({ [atr.substr(7)]: { [Op.gt]: query[atr]} });
      } else if(atr.substr(0, 5) == "_end_"){
        conds.push({ [atr.substr(5)]: { [Op.lt]: query[atr]} });
      } else if (atr != "attributes") {
        conds.push({ [atr]: query[atr] });
      } 
    }
  }
  return where;
};

let removewhere = function (where, field) {
  let cutidx = where[Op.and].findIndex((item) => item[field] != null);
  if (cutidx >= 0) {
    where[Op.and].splice(cutidx, 1);
  }
};
exports.removewhere = removewhere;

exports.setlike = function (where, field, req) {
  if (req.query[field]) {
    removewhere(where, field);
    let op = { [field]: { [Op.like]: `%${req.query[field]}%` } };
    where[Op.and].push(op);
  }
};
